package b1.mobile.blackberry.util;

import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;

import net.rim.device.api.io.transport.ConnectionDescriptor;
import net.rim.device.api.io.transport.ConnectionFactory;
import net.rim.device.api.io.transport.TransportInfo;

public class PDFDownloadUtil {
	
	static int[] preferredTransportTypes = {TransportInfo.TRANSPORT_TCP_WIFI
			, TransportInfo.TRANSPORT_TCP_CELLULAR
			, TransportInfo.TRANSPORT_WAP2
			, TransportInfo.TRANSPORT_WAP};	
	
	public static void DownloadFile(String remoteFile, String localfile) {
//		int startByte = 0;
//		int offset = 1024*60;
		try {
			FileConnection dest = (FileConnection) Connector.open(localfile, Connector.READ_WRITE);
			if(dest.exists()){
				dest.delete();
			}
			dest.create();
			
			OutputStream outStream = dest.openOutputStream();

//			while (true) {
			ConnectionFactory factory = new ConnectionFactory();
			factory.setPreferredTransportTypes(preferredTransportTypes);
			ConnectionDescriptor connDescriptor = factory.getConnection(remoteFile);
			HttpConnection connection = null;
			InputStream inputStream = null;

			connection = (HttpConnection) connDescriptor.getConnection();
//			Connector.open(remoteFile,Connector.READ_WRITE, true);
			connection.setRequestMethod("GET");			

//				connection.setRequestProperty("Range", "bytes=" + startByte
//						+ "-" + ((startByte += offset) - 1));
			int responseCode = connection.getResponseCode();
			if (responseCode != 200 && responseCode != 206) {
				return;
			}
			
			inputStream = connection.openInputStream();
			byte[] Buffer = new byte[1024];
			int length = -1;
			while ((length = inputStream.read(Buffer)) > 0) {
				outStream.write(Buffer, 0, length);
			}

			connection.close();
//			}
			outStream.close();
			
			//openPDF
			OpenFileUtil.openFile(localfile);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
